import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit, TemplateRef, viewChild, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { finalize, map } from 'rxjs';

import { JsonPatchData } from '@app/core/domain/json-patch-data';
import { RequestParams } from '@app/core/domain/request-params';
import { AdminUser, AdminUserService } from '@app/core/services/http/admin-user/admin-user.service';
import { DeptService } from '@app/core/services/http/system/dept.service';
import { UserDepartmentService } from '@app/core/services/http/system/user-dept.service';
import { UserInfo, UserInfoService } from '@app/core/services/store/common-store/userInfo.service';
import { AntTableComponent, AntTableConfig, SortFile } from '@app/shared/components/ant-table/ant-table.component';
import { CardTableWrapComponent } from '@app/shared/components/card-table-wrap/card-table-wrap.component';
import { PageHeaderComponent, PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { WaterMarkComponent } from '@app/shared/components/water-mark/water-mark.component';
import { ModalBtnStatus } from '@app/widget/base-modal';
import { NzAvatarModule } from 'ng-zorro-antd/avatar';
import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageModule, NzMessageService } from 'ng-zorro-antd/message';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzSwitchModule } from 'ng-zorro-antd/switch';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

import { DeptTreeComponent } from '../dept-tree/dept-tree.component';
import { UserModalComponent } from '../user-modal/user-modal.component';
import { UserModalService } from '../user-modal/user-modal.service';

export interface PageSearchParams {
  Name: string;
  UserIds: number[];
}

@Component({
  selector: 'app-user-table',
  standalone: true,
  imports: [
    NzMessageModule,
    PageHeaderComponent,
    FormsModule,
    NzFormModule,
    NzGridModule,
    NzInputModule,
    NzButtonModule,
    NzIconModule,
    CardTableWrapComponent,
    AntTableComponent,
    CommonModule,
    NzPopconfirmModule,
    NzBadgeModule,
    NzSpaceModule,
    NzCardModule,
    WaterMarkComponent,
    UserModalComponent,
    NzSwitchModule,
    DeptTreeComponent,
    NzAvatarModule
  ],
  templateUrl: './user-table.component.html',
  styleUrl: './user-table.component.less'
})
export class UserTableComponent implements OnInit {
  pageSearchParam: Partial<PageSearchParams> = {};
  @ViewChild('highLightTpl', { static: true }) highLightTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('availableFlag', { static: true }) availableFlag!: TemplateRef<NzSafeAny>;
  @ViewChild('userAvatar', { static: true }) avatar!: TemplateRef<NzSafeAny>;
  isCollapse = true;
  tableConfig!: AntTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '账号管理',
    breadcrumb: ['首页', '功能菜单', '账号管理']
  };
  destroyRef = inject(DestroyRef);
  studentClassList: AdminUser[] = [];
  checkedCashArray: NzSafeAny[] = [];
  previousUserInfo!: UserInfo;
  constructor(
    private readonly message: NzMessageService,
    private readonly userModalService: UserModalService,
    private readonly adminUserService: AdminUserService,
    private readonly userInfoService: UserInfoService,
    private readonly cdr: ChangeDetectorRef,
    private readonly router: Router
  ) {}

  private initTable(): void {
    this.tableConfig = {
      headers: [
        {
          title: '头像',
          width: 130,
          field: 'avatar',
          show: true,
          showSort: true,
          tdTemplate: this.avatar
        },
        {
          title: '是否可用',
          width: 100,
          field: 'deactivated',
          tdTemplate: this.availableFlag
        },
        {
          title: '用户名',
          width: 130,
          field: 'username',
          show: true,
          showSort: true
        },
        {
          title: '手机号',
          width: 130,
          field: 'phone',
          show: true,
          showSort: true
        },
        {
          title: '角色',
          width: 130,
          field: 'rolenames',
          show: true,
          showSort: true
        },
        {
          title: '最后登录时间',
          width: 120,
          field: 'lastlogintime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 120,
          fixed: true,
          fixedDir: 'right'
        }
      ],
      total: 0,
      showCheckbox: true,
      loading: false,
      pageSize: 10,
      pageIndex: 1
    };
  }

  selectedChecked(e: NzSafeAny): void {
    this.checkedCashArray = [...e];
  }

  resetForm(): void {
    this.pageSearchParam = {};
    this.search();
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

  reloadTable(): void {
    this.message.info('已经刷新了');
    this.getAdminUserList();
  }

  tableChangeDectction(): void {
    this.studentClassList = [...this.studentClassList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  appendRequestParams(): RequestParams {
    const filter: Partial<AdminUser> = {};
    let requestParams: RequestParams = {
      '@relationships': 'LoginInfo,Password,UserRole',
      current: this.tableConfig.pageIndex,
      pageSize: this.tableConfig.pageSize,
      '@filter': '',
      ...filter
    };

    if (this.pageSearchParam.Name) {
      requestParams['@filter'] += `contains(UserName,${this.pageSearchParam.Name})`;
    }

    return requestParams;
  }

  getAdminUserList(e?: NzTableQueryParams): void {
    if (e) {
      this.tableConfig.pageIndex = e?.pageIndex;
    }
    this.checkedCashArray = [...this.checkedCashArray];
    this.tableConfig.loading = true;
    let requestParams: RequestParams = this.appendRequestParams();

    this.adminUserService
      .getEntityPageList(requestParams)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        map(item => {
          return {
            ...item,
            records: item.records.map(r => {
              const roleNames: string = r.userroles?.map(r => r.rolename).join(',') ?? '';
              return {
                ...r,
                rolenames: roleNames
              };
            })
          };
        })
      )
      .subscribe(students => {
        const { records, total } = students;
        this.studentClassList = records;
        this.tableConfig.total = total;
      });
  }

  changeSort(e: SortFile): void {
    //e.fileName , e.sortDir
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getAdminUserList();
  }

  /*查看*/
  check(name: string): void {
    // skipLocationChange导航时不要把新状态记入历史时设置为true
    this.router.navigate(['default/page-demo/list/search-table/search-table-detail', name, 123]);
  }

  add(): void {
    this.userModalService
      .show({ nzTitle: '新增' })
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(res => {
        if (!res || res.status === ModalBtnStatus.Cancel) {
          return;
        }
        const param = { ...res.modalValue };
        this.tableLoading(true);
        this.addEditData(param, 'addEntity');
      });
  }

  addEditData(param: AdminUser, methodName: 'editEntity' | 'addEntity'): void {
    this.adminUserService[methodName]([param])
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(() => {
        this.previousUserInfo.userentity.avatar = param.avatar;
        this.userInfoService.setUserInfo(this.previousUserInfo);
        this.getAdminUserList();
      });
  }

  allDel(): void {}

  edit(id: number): void {
    this.adminUserService
      .getEntityById(id, { '@relationships': 'UserRole,PassWord,DeptInfo' })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(res => {
        this.userModalService
          .show({ nzTitle: '编辑' }, res[0])
          .pipe(
            finalize(() => {
              this.tableLoading(false);
            }),
            takeUntilDestroyed(this.destroyRef)
          )
          .subscribe(({ modalValue, status }) => {
            if (status === ModalBtnStatus.Cancel) {
              return;
            }
            modalValue.id = id;
            this.tableLoading(true);
            this.addEditData({ ...modalValue, isadmin: res[0].isadmin }, 'editEntity');
          });
      });
  }

  del(id: number): void {
    this.adminUserService.delEntities([id]).subscribe(result => {
      this.getAdminUserList();
    });
  }

  ngOnInit(): void {
    this.initTable();
    this.userInfoService
      .getUserInfo()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(userInfo => {
        this.previousUserInfo = userInfo;
      });
  }
}
